//
//  HybridHandlerCenter.swift
//  MeenoHybrid
//
//  Created by alyadan on 2016/10/15.
//  Copyright © 2016年 alyadan. All rights reserved.
//

import Foundation

public protocol WebViewJavascriptBridgeProtocol{
    
    func registerHandler(handlerName:String, wvjbHandler:@escaping WVJBHandler)
    
}

public protocol HybridHandlerProtocol: NSObjectProtocol{
    
     func register(bridge: WebViewJavascriptBridgeProtocol, webViewModel: HybridBaseWebViewModel)
    
}

extension WebViewJavascriptBridge: WebViewJavascriptBridgeProtocol{
    
    public func registerHandler(handlerName: String,
                                wvjbHandler:@escaping WVJBHandler) {
        
        self.registerHandler(handlerName, handler: wvjbHandler)
        
    }
    
}

extension WKWebViewJavascriptBridge: WebViewJavascriptBridgeProtocol{
    public func registerHandler(handlerName: String, wvjbHandler:@escaping WVJBHandler) {
        
        self.registerHandler(handlerName, handler: wvjbHandler)
        
    }
}



public class HybridHandlerCenter: NSObject, HybridHandlerProtocol {
    

    
    
    // H5 handlers
    static let H5MainHandler = "testJavascriptHandler"
    
    // H5 handlers end
    
    public static let share = HybridHandlerCenter()
    
    
    private var handlers =  [NSObject.Type]()
    
    public func addHandler(type: NSObject.Type) -> Bool{
        if !type.isSubclass(of: HybridBaseHandler.self) {
            return false
        }
        
        let isContain = handlers.contains { (x:NSObject.Type) -> Bool in
            return x == type
        }
        
        if !isContain {
            handlers.append(type)
        }
        
        return true
    }
    
    private override init () {
        super.init()
        
    }
    
    public  func register(bridge: WebViewJavascriptBridgeProtocol, webViewModel: HybridBaseWebViewModel) {
        
        for handler in handlers {
            let x = handler.init()
            if ( x.isKind(of: HybridBaseHandler.self)){
                (x as? HybridBaseHandler)?.register(bridge: bridge, webViewModel: webViewModel)
            }
        }
    }
    
}
